package cn.edu.sie.learnspringboot.controller;

import cn.edu.sie.learnspringboot.domain.Book;
import cn.edu.sie.learnspringboot.service.IBookService;
import cn.edu.sie.learnspringboot.controller.utils.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private IBookService iBookService;

    @GetMapping
    public R getAll(){
        return new R(true, iBookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if (book.getName().equals("qwe")) throw new IOException();
        boolean flag = iBookService.save(book);
        return new R(flag, flag? "添加成功": "添加失败");
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(iBookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(iBookService.removeById(id));
    }

    @GetMapping("{id}")
    public R selectGetById(@PathVariable Integer id) {
        return new R(true, iBookService.getById(id));
    }

    @GetMapping("{c}/{s}")
    public R getPage(@PathVariable int c, @PathVariable int s, Book book){
        System.out.println("数量 " + c + "长度 " + s + "book " + book);

        IPage<Book> page = iBookService.getPage(c, s, book);
        if (c > page.getPages()) {
            page = iBookService.getPage((int) page.getPages(), s, book);
        }
        return new R(true, page);
    }
}
